package com.ddd.mill.domain.aggregate.sku;

import com.ddd.mill.domain.aggregate.product.entity.Product;
import com.ddd.mill.domain.aggregate.producttype.repository.ProductTypeRepository;
import com.ddd.mill.domain.aggregate.sku.entity.ProductSku;
import com.ddd.mill.domain.aggregate.sku.entity.ProductSkuValue;
import com.ddd.mill.api.product.dto.request.SaveProductByAdminDto;
import com.ddd.mill.domain.aggregate.attributevalue.repository.AttributeValueRepository;
import com.ddd.mill.domain.aggregate.sku.repository.ProductSkuRepository;
import com.ddd.mill.domain.aggregate.sku.repository.ProductSkuValueRepository;
import com.ddd.mill.infrastructure.exception.BizException;
import com.ddd.mill.infrastructure.persistent.domain.BaseAggregate;
import com.ddd.mill.query.attributevalue.AttributeValueQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class ProductSkuAggregate extends BaseAggregate {

    @Resource
    ProductTypeRepository productTypeRepository;
    @Resource
    AttributeValueRepository attributeValueRepository;
    @Resource
    AttributeValueQueryService attributeValueQueryService;
    @Resource
    ProductSkuValueRepository productSkuValueRepository;
    @Resource
    ProductSkuRepository productSkuRepository;

    public void saveProductSku(SaveProductByAdminDto dto, Long adminId,Long productId){

    }
    public void copyProductSku(Long adminId, Product product){
        Long productId=product.getId();
        // sku
        List<ProductSku> productSkuList = productSkuRepository.getListByProductId(productId);
        List<ProductSkuValue> productSkuValueList = new ArrayList<>();
        Map<Long, List<ProductSkuValue>> productSkuValueMap = productSkuValueRepository.getListBySkuList(productSkuList);
        for (ProductSku p : productSkuList){
            List<ProductSkuValue> productSkuValues = productSkuValueMap.get(p.getId());
            p.setId(null);
            p.setProductId(productId);
            p.setCreatorId(adminId);
            p.setEditorId(adminId);
            if (null==productSkuRepository.save(p)){
                throw new BizException(product.getName()+"产品复制失败");
            }
            for (ProductSkuValue v : productSkuValues){
                v.setId(null);
                v.setSkuId(p.getId());
                v.setCreatorId(adminId);
                v.setEditorId(adminId);
            }
            productSkuValueList.addAll(productSkuValues);
        }
        productSkuValueRepository.saveBatch(productSkuValueList);
    }
}
